﻿using HalkSee.Helper;
using System.IO.Compression;
using Microsoft.Maui.Controls;
using Android.Graphics;
using System.Text;
using Android.OS;

namespace HalkSee;

public partial class MainPage : ContentPage
{
	public MainPage()
	{
		InitializeComponent();
	}

    private void ContentPage_Loaded(object sender, EventArgs e)
    {
        var freeSpace = new StatFs(FileSystem.AppDataDirectory).AvailableBytes / 1024 / 1024 / 1024;
        lbl.Text = $"设备编号:{InfoHelper.SN}, 可用空间:{freeSpace:F0}GB";

        barcodeImage.Barcode = $"{InfoHelper.SN} {InfoHelper.MyOtpKey}";

        MqttHelper.StatusChange(status =>
        {
            MainThread.BeginInvokeOnMainThread(() =>
            {
                if(status == -1)
                    lblStatus.Text = "连接网络失败";
                if (status == 0)
                    lblStatus.Text = "连接中...";
                if (status == 1)
                    lblStatus.Text = "连接成功";
            });
        });

        MqttHelper.MsgCallback(async (topic, data) =>
        {
            //理论先验证

            //获取实时图片
            if (topic == $"/record/{InfoHelper.SN}/now")
            {
                //var backTopic = System.Text.Encoding.UTF8.GetString(data);

                //var imgs = cameraView.GetSnapShot(Camera.MAUI.ImageFormat.JPEG);
                //if (imgs != null)
                //{
                //    using var stream = await ((StreamImageSource)imgs).Stream(CancellationToken.None);
                //    if (stream != null)
                //    {
                //        using var ms = new MemoryStream();
                //        await stream.CopyToAsync(ms);
                //        ms.Position = 0;

                //        using var newData = new MemoryStream();
                //        var map = await BitmapFactory.DecodeStreamAsync(ms);
                //        var newMap = Bitmap.CreateScaledBitmap(map, 600, 400, true);
                //        newMap.Compress(Bitmap.CompressFormat.Jpeg, 30, newData);

                //        var bytes = newData.ToArray();

                //        //var now = DateTime.Now;
                //        //var filename = $"{now:HHmmssfff}.jpg";
                //        //await FileHelper.WriteFileAsync(now.ToString("yyyyMMdd"), filename, bytes);

                //        await MqttHelper.PublishAsync(backTopic, bytes);
                //    }
                //    else
                //    {
                //        Debug.WriteLine("stream is null ");
                //    }
                //}
                //else
                //{
                //    Debug.WriteLine("imgs is null ");
                //}
            }
            //请求获取所有文件名
            if (topic == $"/req/{InfoHelper.SN}/list")
            {
                var arr = Encoding.UTF8.GetString(data).Trim().Split(' ');
                if(!InfoHelper.VerifyOtpCode(InfoHelper.MyOtpKey, arr[1]))
                {
                    Console.WriteLine("验证失败，不予应答");
                    return;
                }
                var files = FileHelper.GetFiles(FileSystem.Current.AppDataDirectory);
                byte[] bytes = null;
                if (files?.Length > 0)
                {
                    bytes = Encoding.UTF8.GetBytes(string.Join(' ', files));
                }
                else
                {
                    bytes = Encoding.UTF8.GetBytes("nofiles");
                }
                await MqttHelper.PublishAsync($"/rsp/{arr[0]}/list", bytes);
            }
            //请求获取一个文件
            if (topic == $"/req/{InfoHelper.SN}/file")
            {
                var arr = Encoding.UTF8.GetString(data).Trim().Split(' ');
                if (!InfoHelper.VerifyOtpCode(InfoHelper.MyOtpKey, arr[2]))
                {
                    Console.WriteLine("验证失败，不予应答");
                    return;
                }
                using var ms = new MemoryStream();
                ms.Write(System.Text.Encoding.UTF8.GetBytes(arr[1]));
                ms.Write(FileHelper.GetFile(FileSystem.Current.AppDataDirectory, arr[1]));
                await MqttHelper.PublishAsync($"/rsp/{arr[0]}/file", ms.ToArray());
            }

        });
        MqttHelper.Start("10.6.14.188", 1883, InfoHelper.SN, "admin", "123456");
    }

	private async void OnCounterClicked(object sender, EventArgs e)
	{
        var status1 = await Permissions.CheckStatusAsync<Permissions.Camera>();
        var status2 = await Permissions.CheckStatusAsync<Permissions.Microphone>();
        var status3 = await Permissions.CheckStatusAsync<Permissions.StorageWrite>();
        lbl.Text = $"设备编号:{InfoHelper.SN},摄像头{status1},麦{status2},存储{status3}";

        if (status1 != PermissionStatus.Granted)
        {
            await DisplayAlert("提示", "请授权使用摄像头", "好的");
            status1 = await Permissions.RequestAsync<Permissions.Camera>();
        }
        if (status2 != PermissionStatus.Granted)
        {
            await DisplayAlert("提示", "请授权麦克风", "好的");
            status2 = await Permissions.RequestAsync<Permissions.Microphone>();
        }
        if (status3 != PermissionStatus.Granted)
        {
            await DisplayAlert("提示", "请授权存储", "好的");
            status3 = await Permissions.RequestAsync<Permissions.StorageWrite>();
        }
        lbl.Text = $"设备编号:{InfoHelper.SN},摄像头{status1},麦{status2},存储{status3}";
    }

    private async void Button_Clicked(object sender, EventArgs e)
    {
        await Navigation.PushAsync(new RecordEye(), true);
    }

    private async void Button_Clicked_1(object sender, EventArgs e)
    {
        await Navigation.PushAsync(new ShowDevice(), true);
    }

}

